import threading
import time

from ProtocolParser import ProtocolParser
from sqlite_tool import SQLiteTool


class DatabaseQueryTimer:
    def __init__(self):
        self._db_tool = SQLiteTool()
        self._protocol_parser = ProtocolParser()
        self._timer_thread = None
        self._running = False
        self.check_id = None

    def _timer_loop(self, info_id, client_sock, level):
        while self._running:
            self._execute_query(info_id, client_sock, level)
            time.sleep(1)  # Wait for 1 second

    def _execute_query(self, info_id, client_sock, level):
        if self.check_id is None:
            _query = f'SELECT id FROM T_CHECK_RSLT WHERE param_id = {info_id} ORDER BY id DESC'
            res = self._db_tool.query(_query)
            if res:
                self.check_id = res[0][0]
            print('查询check_id', res)
        if self.check_id:
            _query = f'SELECT check_point, load_flag, asc_ratio_err, asc_angle_err FROM T_ERROR_DET WHERE check_id = {self.check_id} ' \
                     f'ORDER BY CAST(check_point AS INTEGER), CAST(load_flag AS INTEGER)'
            results = self._db_tool.query(_query)
            # print(results)
            if results:
                self._protocol_parser.construct(self, results, client_sock, level)

    def control_callback(self, command, info_id=None, client_sock=None, level=None):
        if command == "start":
            if not self._running:
                self._running = True
                self._timer_thread = threading.Thread(target=self._timer_loop, args=(info_id, client_sock, level))
                self._timer_thread.start()
        elif command == "stop":
            if self._running:
                self._running = False
                self.check_id = None
                if self._timer_thread.is_alive():
                    # 检查当前线程是否不是_timer_thread
                    if threading.current_thread() != self._timer_thread:
                        self._timer_thread.join()  # 等待线程完成
        else:
            print(f"Unknown command: {command}")
